//
//  YCBaseViewController.m
//  LOLBox
//
//  Created by mac on 15-3-12.
//  Copyright (c) 2015年 Honey. All rights reserved.
//

#import "YCBaseViewController.h"
#import "AFNetworking.h"
#import "YCNewSModel.h"
#import "YCNewTableViewCell.h"
#import "YCDetailsViewController.h"
#import "HXADBanner.h"
#import "MJRefresh.h"
#import "YCAppDelegate.h"

# define iphone5  ( fabs( ( double )[ [ UIScreen mainScreen ] bounds ].size.height - ( double )568 ) < DBL_EPSILON )
#define NewestUrl @"http://lolbox.oss.aliyuncs.com/json/v3/news/newslist_99_%d.json"
#define kBanner @"http://lolbox.oss.aliyuncs.com/json/v3/news/banner.json?r=692777"

@interface YCBaseViewController ()<MJRefreshBaseViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    HXADBanner *_banner;
    NSInteger _page;
    BOOL _isFirst;
    
    // 刷新
    MJRefreshFooterView *_footerView;
    MJRefreshHeaderView *_headerView;
    MJRefreshBaseView *_baseView;

}

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataSource;

@end

@implementation YCBaseViewController

- (void)viewWillAppear:(BOOL)animated
{
    YCAppDelegate *delegate = [UIApplication sharedApplication].delegate;
    [delegate showTabBar];
    animated = YES;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        _isFirst = YES;
                
        self.title = @"新闻资讯";
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 64)];
        label.text = @"新闻资讯";
        label.font = [UIFont boldSystemFontOfSize:17];
        label.textColor = [UIColor whiteColor];
        label.textAlignment = NSTextAlignmentCenter;
        
        self.navigationItem.titleView = label;
        
        self.dataSource = [NSMutableArray array];
    }
    return self;
}

- (void)viewDidLoad
{
    _page = 1;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createimg];
    [self createBanner];
    /**
     *  初始化导航条下面的导航条
     */
//    [self createNavView];
    
    /**
     数据请求
     */
    [self AFN:NewestUrl WithDict:nil];
    
    /**
     实例化TableView
     */
    [self initTableView];

    [self initFooterView];
    [self initHeaderView];

}

//滚动视图
- (void)createBanner
{
    _banner = [[HXADBanner alloc] init];
    _banner.frame = CGRectMake(0, 0, 320, 140);
    
    NSMutableArray *dataArr = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:kBanner parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];

        [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            NSString *img = obj[@"img"];
            if (img.length != 0)
            {
                [dataArr addObject:img];
            }
        }];
        
        _banner.arrays = dataArr;
        [_banner setArrays:dataArr];
        //[self.view addSubview:_banner];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"错误");
    }];

    
}


//- (void)createNavView
//{
//    YCNavView *navView = [[YCNavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 35)];
//    [navView changValue:@"123" senderBlock:^(NSString *senderStr) {
//        
//        BOOL bbk = [senderStr isEqualToString:NewestUrl];
//        if (bbk)
//        {
//            _isFirst = YES;
//            [self createBanner];
//            self.tableView.tableHeaderView = _banner;
//            //[self.tableView reloadData];
//        }
//        else
//        {
//            _isFirst = NO;
//            self.tableView.tableHeaderView = nil;
//        }
//        
//        [self AFN:senderStr WithDict:nil];
//    }];
//    [self.view addSubview:navView];
//}
//
- (void)initTableView
{
    //CGRect rect = [UIScreen mainScreen].bounds;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 35, self.view.frame.size.width, self.view.frame.size.height - 64 - 50 - 35) style:UITableViewStylePlain];
    
    //self.tableView = [[UITableView alloc] initWithFrame:rect style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 95;
    //self.tableView.sectionHeaderHeight = 300;
    if (_isFirst)
    {
        self.tableView.tableHeaderView = _banner;
    }
    self.tableView.backgroundColor = [UIColor redColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    /**
     *  去掉多余的线
     */
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = [UIColor clearColor];
    self.tableView.tableFooterView = v;
    
    // 注册Cell
    [self.tableView registerClass:[YCNewTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.view addSubview:self.tableView];
    
}

- (void)AFN:(NSString *)str WithDict:(NSDictionary *)dict
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manager GET:[NSString stringWithFormat:str,_page] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        //NSLog(@"%@",dict);
//        if (self.dataSource.count > 0)
//        {
//            [self.dataSource removeAllObjects];
//        }
        [dict enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            //NSLog(@"-------------------");
            //NSLog(@"%@",obj);
            YCNewSModel *model = [[YCNewSModel alloc] init];
            model.desc = obj[@"desc"];
            model.Id = obj[@"id"];
            model.img = obj[@"img"];
            model.posttime = obj[@"posttime"];
            model.site = obj[@"site"];
            model.thumb_img = obj[@"thumb_img"];
            model.thumb_ok = obj[@"thumb_ok"];
            model.title = obj[@"title"];
            model.topic_id = obj[@"topic_id"];
            
            //NSLog(@"title:%@",model.title);
            [self.dataSource addObject:model];
        }];
        [self.tableView reloadData];
        
        if (_headerView == _baseView)
        {
            [_headerView endRefreshing];
        }
        if (_footerView == _baseView)
        {
            
            [_footerView endRefreshing];
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"fail");
        if (_headerView == _baseView)
        {
            [_headerView endRefreshing];
        }
        if (_footerView == _baseView)
        {
            
            [_footerView endRefreshing];
        }

    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YCNewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    if (self.dataSource.count > 0)
    {
        YCNewSModel *model = self.dataSource[indexPath.row];
        [cell fillCellWithModel:model];
    }
    return cell;
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 95;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YCNewSModel *model = self.dataSource[indexPath.row];
    YCDetailsViewController *details = [[YCDetailsViewController alloc] init];
    //NSLog(@"sss:%@",model.Id);
    self.navigationController.hidesBottomBarWhenPushed = YES;
    [details senderNewsModel:model];
    //_Block();
    [self.navigationController pushViewController:details animated:YES];
    //self.tabBarController.tabBar.hidden = YES;
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)createimg
{
    UIImageView *v = [[UIImageView alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.frame), 320, 50)];
    v.backgroundColor = [UIColor blackColor];
    [self.view addSubview:v];
}


- (void)dealloc
{
    [_headerView free];
    [_footerView free];
}

- (void)initHeaderView
{
    _headerView = [[MJRefreshHeaderView alloc] initWithScrollView:_tableView];
    _headerView.delegate = self;
}

- (void)initFooterView
{
    _footerView = [[MJRefreshFooterView alloc] initWithScrollView:_tableView];
    _footerView.delegate = self;
}

#pragma mark - MJRefreshBaseViewDelegate

- (void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    _baseView = refreshView;
    
    if (_baseView == _headerView)
    {
        NSLog(@"刷新");
        
        if (_dataSource.count > 0)
        {
            [_dataSource removeAllObjects];
        }
        _page = 1;
    }
    else
    {
        NSLog(@"加载更多");
        _page++;
    }
    
    //NSLog(@"see%d",_page);
    [self AFN:NewestUrl WithDict:nil];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
